import os
import re
import time
import sys
import traceback

def get_actual_path():
    """获取实际运行路径"""
    if getattr(sys, 'frozen', False):
        # 如果是打包后的exe在运行
        return os.path.dirname(sys.executable)
    else:
        # 如果是python脚本在运行
        return os.path.dirname(os.path.abspath(__file__))

def convert_txt_to_vtt(input_file, output_file):
    try:
        # 读取输入文件
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 初始化VTT内容
        vtt_content = "WEBVTT\n\n"
        
        # 转换每一行
        for line in lines:
            # 使用正则表达式匹配时间戳和文本内容
            match = re.match(r'\[(\d{2}:\d{2}.\d{3})\s->\s(\d{2}:\d{2}.\d{3})\]\s(.+)', line)
            if match:
                start_time = f"00:{match.group(1)}"
                end_time = f"00:{match.group(2)}"
                text = match.group(3)
                vtt_content += f"{start_time} --> {end_time}\n{text}\n\n"
        
        # 写入输出文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(vtt_content)
        return True
    except Exception as e:
        print(f"处理文件 {input_file} 时出错: {str(e)}")
        print(f"详细错误信息: {traceback.format_exc()}")
        return False

def main():
    try:
        # 获取实际运行路径
        current_dir = get_actual_path()
        print(f"当前工作目录: {current_dir}")
        
        # 确保工作目录正确
        os.chdir(current_dir)
        
        # 找出所有txt文件
        txt_files = [f for f in os.listdir(current_dir) if f.endswith('.txt')]
        
        if not txt_files:
            print("当前目录下没有找到txt文件！")
            print("请确保txt文件与程序在同一目录下")
            print("\n按回车键退出...")
            input()
            return
        
        # 转换计数
        success_count = 0
        fail_count = 0
        
        print(f"\n找到 {len(txt_files)} 个txt文件")
        print("开始转换...")
        print("-" * 50)
        
        # 处理每个txt文件
        for txt_file in txt_files:
            input_path = os.path.join(current_dir, txt_file)
            output_path = os.path.join(current_dir, txt_file.rsplit('.', 1)[0] + '.vtt')
            
            print(f"正在处理: {txt_file}")
            if convert_txt_to_vtt(input_path, output_path):
                success_count += 1
                print(f"成功: {txt_file} -> {txt_file.rsplit('.', 1)[0] + '.vtt'}")
            else:
                fail_count += 1
                print(f"失败: {txt_file}")
            print("-" * 50)
        
        # 显示统计结果
        print(f"\n转换完成！")
        print(f"成功: {success_count} 个文件")
        print(f"失败: {fail_count} 个文件")
        print("\n按回车键退出...")
        input()
        
    except Exception as e:
        print(f"程序运行出错: {str(e)}")
        print(f"详细错误信息: {traceback.format_exc()}")
        print("\n按回车键退出...")
        input()

if __name__ == "__main__":
    main()